package com.woniuxy.lrz.carlproject.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.woniuxy.lrz.carlproject.common.AppException;
import com.woniuxy.lrz.carlproject.common.util.OssTemplate;
import com.woniuxy.lrz.carlproject.common.util.Results;
import com.woniuxy.lrz.carlproject.controller.form.formgoods.GoodsInfoAOUForm;
import com.woniuxy.lrz.carlproject.controller.form.formgoods.GoodsInfoFindForm;
import com.woniuxy.lrz.carlproject.model.GoodAttachment;
import com.woniuxy.lrz.carlproject.model.ServiceInfo;
import com.woniuxy.lrz.carlproject.service.GoodInfoService;
import com.woniuxy.lrz.carlproject.service.ServiceInfoService;
import com.woniuxy.lrz.carlproject.service.dto.dtocar.CarDetailsTypeBrandDto;
import com.woniuxy.lrz.carlproject.service.dto.dtogoods.GoodsCarAndAttachDto;
import com.woniuxy.lrz.carlproject.service.dto.dtogoods.GoodsInfoByServiceAndCarDto;
import com.woniuxy.lrz.carlproject.service.dto.dtogoods.GoodsInfoDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品表 前端控制器
 * </p>
 *
 * @author lrz
 * @since 2022-09-28
 */
@RestController
@Slf4j
@Api(tags = "商品接口")
@Validated
@RequestMapping("/carlproject/goodInfo")
public class GoodInfoController {
    @Resource
    private GoodInfoService goodInfoService;
    @Resource
    private ServiceInfoService serviceInfoService;

    @GetMapping("/loadGoodsByServiceAndCar")
    @ApiOperation("根据服务Id和车型详情ID加载商品")
    public Results loadGoodsByServiceAndCar(Integer serviceId,Integer carDetailId) throws JsonProcessingException {
        if(serviceId==null){
            throw new AppException("服务Id不能为空");
        }
        if(carDetailId==null){
            throw new AppException("车型详情Id不能为空");
        }
        List<GoodsInfoByServiceAndCarDto> goodsInfoByServiceAndCarDtos = goodInfoService.loadGoodsByServiceAndCar(serviceId, carDetailId);
        return Results.instance().setData(goodsInfoByServiceAndCarDtos).setMessage("根据服务Id和车型详情ID加载商品成功");
    }

    @PostMapping("/addGoodInfo")
    @ApiOperation("新增/修改商品信息")
    public Results addGoodInfo(@RequestBody @Valid GoodsInfoAOUForm goodsInfoAOUForm){
        log.info("商品信息:{}",goodsInfoAOUForm);
        goodInfoService.addGoodInfo(goodsInfoAOUForm);
        return Results.instance().setMessage("操作成功");
    }

    @PostMapping("/goodPhotos")
    @ApiOperation("上传商品图片")
    public Results commentPhoto(@NotEmpty(message = "商品图片不能为空") MultipartFile[] images) throws IOException {
        //声明一个返回前端的文件信息集合
        ArrayList<GoodAttachment> goodAttachments=new ArrayList<>();
        //循环获取上传文件信息并存到云端
        for (int i = 0; i < images.length; i++) {
            //原文件名
            String oldName = images[i].getOriginalFilename();
            //传到云服务器（不用改动）
            String s = OssTemplate.fileUpload("img/"+oldName,images[i].getInputStream(), "woniuxy-81-3");
            //文件大小
            long size = images[i].getSize();
            //后缀
            String fileSuffix = oldName.substring(oldName.lastIndexOf(".") + 1, oldName.length());
            //路径（前端可以拿来做展示）
            String filePath=s;
            //现文件名
            String fileName=s;

            GoodAttachment goodAttachment=new GoodAttachment();
            goodAttachment.setFileSuffix(fileSuffix);
            goodAttachment.setIlePath(filePath);
            goodAttachment.setNewFile(fileName);
            goodAttachment.setOldFile(oldName);
            goodAttachment.setSize(size);
            //返回URL，前端调用显示
            goodAttachments.add(goodAttachment);
        }
        return Results.success(200,"文件上传成功",goodAttachments);
    }

    @DeleteMapping("/deleteGoods")
    @ApiOperation("删除商品")
    @ApiImplicitParam(name = "goodId",value = "商品Id")
    public Results deleteGoods(Integer goodId){
        if(goodId==null){
            throw new AppException("商品Id不能为空");
        }
        goodInfoService.deleteGoods(goodId);
        return Results.instance().setMessage("删除成功");
    }

    @GetMapping("/findGoodsInfo")
    @ApiOperation("查询商品信息")
    public Results findGoodsInfo(@Valid GoodsInfoFindForm goodsInfoFindForm){
        Page<GoodsInfoDto> goodsInfo = goodInfoService.findGoodsInfo(goodsInfoFindForm);
        return Results.instance().setMessage("查询商品信息成功").setData(goodsInfo);
    }

    @GetMapping("/findGoodsInfoByGoodId")
    @ApiOperation("根据商品Id查询商品车型和附件信息")
    @ApiImplicitParam(name = "goodId",value ="商品Id" )
    public Results findGoodsInfoByGoodId(Integer goodId){
        if(goodId==null){
            throw new AppException("商品Id不能为空");
        }
        GoodsCarAndAttachDto goodsInfoByGoodId = goodInfoService.findGoodsInfoByGoodId(goodId);
        return Results.instance().setData(goodsInfoByGoodId).setMessage("根据商品Id查询商品车型和附件信息成功");
    }

    @GetMapping("/findServices")
    @ApiOperation("根据二级服务Id加载服务列表")
    @ApiImplicitParam(name = "serviceSecondId",value ="二级服务Id" )
    public Results findServices(Integer serviceSecondId){
        if(serviceSecondId==null){
            throw new AppException("二级服务Id不能为空");
        }
        List<ServiceInfo> service_second_id = serviceInfoService.list(new QueryWrapper<ServiceInfo>().eq("service_second_id", serviceSecondId));
        return Results.instance().setData(service_second_id).setMessage("加载服务列表成功");
    }

    @PostMapping("/goodPhoto")
    @ApiOperation("上传商品封面图片")
    public Results goodPhoto(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        String s = OssTemplate.fileUpload("img/"+originalFilename,inputStream, "woniuxy-81-3");
        log.info("图片URL:{}",s);
        return Results.instance().setData(s);
    }

    @GetMapping("/loadAllCars")
    @ApiOperation("新增商品时加载所有车辆信息")
    public Results loadAllCars(){
        List<CarDetailsTypeBrandDto> carDetailsTypeBrandDtos = goodInfoService.loadAllCars();
        return Results.instance().setData(carDetailsTypeBrandDtos).setMessage("加载所有车辆信息成功");
    }



}
